# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymongo
from python_scrapy.settings import mongo_host, mongo_port, mongo_db_name, mongo_db_collection


class PythonScrapyPipeline:

    def __init__(self):
        host = mongo_host
        port = mongo_port
        db_name = mongo_db_name
        db_collection = mongo_db_collection
        client = pymongo.MongoClient(host=host, port=port)
        # 选择数据库
        my_db = client[db_name]
        # 选择集合
        self.post = my_db[db_collection]

    def process_item(self, item, spider):
        data = dict(item)
        self.post.insert_one(data)
        # print(data)
        return item

    pass
